<?php

namespace app\xcxapi\service;

use app\common\service\BaseService;
use app\lib\exception\BaseException;
use app\models\CampusModel;
use app\models\ClassRoomModel;
use app\models\ClassTimeModel;
use app\models\ContractModel;
use app\models\CourseModel;
use app\models\DictionaryModel;
use app\models\GradesDetailsListsModel;
use app\models\GradesDetailsModel;
use app\models\GradesModel;
use app\models\HolidayModel;
use app\models\CourseLogModel;
use app\models\StudentModel;
use app\models\StudentSubjectClassModel;
use app\models\StudentSubjectInfosClassModel;
use app\models\TeacherModel;
use app\models\UserModel;

class GradesService extends BaseService
{
    /**
     * 节假日信息.
     *
     * @var array
     */
    protected $holiday_arr = [];

    /**
     * @var StudentSubjectClassModel
     */
    protected $studentsubjectclassModel;

    /**
     * @var StudentModel
     */
    protected $studentModel;

    /**
     * @var GradesDetailsListsModel
     */
    protected $gradesDetailsListsModel;

    /**
     * @var GradesDetailsModel
     */
    protected $gradesDetailsModel;

    /**
     * @var StudentSubjectInfosClassModel
     */
    protected $studentsubjectinfosclassModel;

    /**
     * 班级列表
     * User: wufeng
     * Date: 2020/01/11.
     *
     * @param $params
     *
     * @return array
     */
    public function gradesLists($params)
    {
        try {
            $where = [];
			if(xcxapi_get_current_wtype() != 1){
			$where['campus_id'] = ['in', xcxapi_get_current_campus_id()];	
			}
            $where['graduation_status'] = 0;  //未结业
            $this->data = (new GradesDetailsModel())
                ->where($where)
				->order('id desc')
                ->select()
                ->toArray();

            foreach ($this->data as &$val) {
                $arrs = (new StudentSubjectClassModel())->where('class_subject_id', $val['id'])->column('student_id');
                //已报
                $val['already_reported_num'] = \count(array_unique($arrs));
                //教室
                $val['room'] = (implode('|', array_unique(explode(',', $val['room_text']))));

                $gradesDetailsLists = (new GradesDetailsListsModel())->where(['class_manage_id'=>$val['id']])->order('class_date asc')->find();
				$val['first_time'] = $gradesDetailsLists['class_date'].' '.$gradesDetailsLists['class_subject_start'];
                $course = (new CourseModel())->get($val['course_id']);
                //班课类型
                $val['course_type'] = $course['course_type'];
                $val['course_type_text'] = (new DictionaryModel())->get($val['course_type'])['name'];
                //课程名称及课程费用
                $val['course_name'] = $course['course_name'];
                $val['course_total_price'] = $course['total_price'] / 100;
                $val['course_unit'] = $course['unit'];
                $val['course_class_num'] = $course['class_num'];
            }
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	 /**
     * 修改排课
     * User: chenben
     * Date: 2020/04/18.
     *
     * @param $params
     *
     * @return array
     */
    public function getGradesInfo($params)
    {
        try {
        $manage_id = $params['id'];
        $campus_id = $params['campus_id'];
        $grades_list = (new GradesDetailsModel())->get(['id' => $manage_id]);
        $gcourse_name = (new CourseModel())->get(['id' => $grades_list['course_id']])['course_name'];
        $grades_list['course_name'] = $gcourse_name;
        if($grades_list['preoccupation'] == 0){
            $grades_list['preoccupation'] = '无限';
        }
        $data = [];
        $class_time_place_str = $grades_list['class_time_place'];//字符串
        $room_id_arr = explode(",",$grades_list['room_id']);//教室字符串数组
        $time_slot = explode(",",$grades_list['time_slot']);//时间段字符串数组
        $week_record = explode(",",$grades_list['week_record']);//星期字符串数组
        $room_text = explode(",",$grades_list['room_text']);//教室名称字符串数组

        if($grades_list['repeat_status'] == 1){ //按周
            for($index =0; $index < count($room_id_arr); $index ++){
                $item['weekday'] = $week_record[$index];
                $time_arr = explode("-",$time_slot[$index]);
                $item['start_time'] = $time_arr[0];
                $item['end_time'] = $time_arr[1];
                $item['room_text'] = $room_text[$index];
                $item['room_id'] = $room_id_arr[$index];
                $data[] = $item;
            }

         }else if($grades_list['repeat_status'] == 2){  //按日
            $item['weekday'] = $week_record[0];
            $time_arr = explode("-",$time_slot[0]);
            $item['start_time'] = $time_arr[0];
            $item['end_time'] = $time_arr[1];
            $item['room_text'] = $room_text[0];
            $item['room_id'] = $room_id_arr[0];
            $data[] = $item;
        }
		$this->data['class_info'] = $data;
		$this->data['grades_info'] = $grades_list;
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
     * 插入学员
     * User: chenben
     * Date: 2020/04/18
     *
     * @param $params
     *
     * @return array
     */
    public function insertStudentTable($params)
    {
        try {
			$data = $params;
            $studentdata = $data['studentdata'];  //分班学生数据
            $studentdata_delete = $data['studentdata_delete'];  //需要删除已存在的分班学生数据
            $class_id = $data['class_id'];//班级ID
            $room_id = $data['room_id'];  //教室字符串id
            $campus_id = $data['campus_id'];
            $room_classroom = explode(",", $room_id); //获取教室列表
            $room_id_classroom = [];  //教室id
            for ($a = 0; $a < count($room_classroom); $a++) {
                if (!in_array($room_classroom[$a], $room_id_classroom)) {
                    $room_id_classroom[] = $room_classroom[$a];
                }
            }

            $save_data = [];
            $json_student_data = $studentdata;
            $json_student_delete_data = $studentdata_delete;  //需要删除的已分班的学生数据
            if (count($json_student_data) > 0) {
                for ($i = 0; $i < count($json_student_data); $i++) {
                    $item = $json_student_data[$i];
                    for ($j = 0; $j < count($room_id_classroom); $j++) {
                        if($item['status_match'] == 0) {  //先前表里不存在
                            $cell = [];
                            $cell['student_id'] = $item['student_id'];  //学生ID
                            $cell['student_name'] = $item['student_name']; //学生姓名
                            $cell['room_id'] = $room_id_classroom[$j];//教室ID
                            $cell['class_subject_id'] = $class_id;//班级ID
                            $cell['campus_id'] = $campus_id;
                            if($item['type'] == 1){
                                $cell['status'] = 1;//课程
                            }else if($item['type'] == 2){
                                $cell['status'] = 2;//班级
                            }
                            $cell['contract_number'] = $item['contract_number']; //合同编号
                            $save_data[] = $cell;
                        }
                    }

                }

            }

            $delete_student_id = "";
            $delete_student_type = "";
            $delete_student_contract_number = "";
            if(count($json_student_delete_data) > 0){
                for ($i = 0; $i < count($json_student_delete_data); $i++) {
                    $item = $json_student_delete_data[$i];
                    $delete_student_id = $delete_student_id.$item['student_id'].',';
                    $delete_student_type = $delete_student_type.$item['type'].',';
                    $delete_student_contract_number = $delete_student_contract_number.$item['contract_number'].',';
                }


                $delete_student_id = substr($delete_student_id, 0, strlen($delete_student_id)-1);
                $delete_student_type = substr($delete_student_type, 0, strlen($delete_student_type)-1);
                $delete_student_contract_number = substr($delete_student_contract_number, 0, strlen($delete_student_contract_number)-1);
                $where = [];
                $where['student_id'] = ['in',$delete_student_id];
                $where['class_subject_id'] = $class_id;
                $where['status'] = ['in',$delete_student_type];
                $where['contract_number'] = ['in',$delete_student_contract_number];
                if(!(new StudentSubjectClassModel())->where($where)->delete()){
                     throw new BaseException('DELETE_EXCEPTION');
                }
                if((new StudentSubjectInfosClassModel())->where("student_id in ($delete_student_id) AND class_subject_id=$class_id AND status = 0")->count() > 0){
                    $infos_result = (new StudentSubjectInfosClassModel())->where("student_id in ($delete_student_id) AND class_subject_id=$class_id AND status = 0")->select();
                    foreach ($infos_result as $key => $value){
                            if($value['follow_status'] == 2){   //跟班
                                    (new StudentSubjectInfosClassModel())->where(['id' => $value['lessons_id']])->update(['lessons_status' => 0]);
                            }
                    }
                    if(!(new StudentSubjectInfosClassModel())->where("student_id in ($delete_student_id) AND class_subject_id=$class_id AND status = 0")->delete()){
                         throw new BaseException('SCHEDULE_DELETE_EXCEPTION');
                    }


                }

            }

            if(count($json_student_data) > 0){
                $sava_cell_date = [];
                $resullt = (new GradesDetailsListsModel())->where(['class_manage_id' => $class_id])->select();
                foreach ($resullt as $key => $value){
                    $id = $value['id'];
                    $room_id = $value['class_room_id']; //教室ID
                    $room_name = $value['class_room']; //教室名称
                    $class_date = $value['class_date'];//开课日期
                    $weekday = $value['weekday'];//星期
                    $course_id = $value['course_id']; //课程ID
                    $campus_id =  $value['campus_id']; //校区ID
                    $start = strtotime($value['class_subject_start']);  //开始时间
                    $end = strtotime($value['class_subject_end']);  //结束时间
                    $duration = ceil(($end - $start)/60); //节课时长
                    for ($i = 0; $i < count($json_student_data); $i++) {
                        $item = $json_student_data[$i];
                        if($item['status_match'] == 0) {  //先前表里不存在
                            $cell = [];
                            $cell['contract_number'] = $item['contract_number'];  //订单编号ID，非自增ID
                            $cell['student_id'] = $item['student_id'];  //学生ID
                            $cell['student_name'] = $item['student_name']; //学生姓名
                            $cell['surplus_class_elimination'] = $item['course_elimination']; //剩余课时
                            $cell['surplus_class_elimination_give'] = $item['course_elimination_give']; //赠送课时
                            $cell['room_id'] = $room_id;//教室ID
                            $cell['class_subject_id'] = $class_id;//班级ID
                            $cell['class_manage_details_id'] = $id; //ID
                            $cell['room_name'] = $room_name; //教室名称
                            $cell['class_date'] = $class_date; //开班日期
                            //操作人
                            $cell['operatorer'] = get_current_name();  //操作人
                            if($item['type'] == 1){
                                $cell['report_status'] = 1;//课程
                            }else if($item['type'] == 2){
                                $cell['report_status'] = 2;//班级
                            }
                            $cell['course_id'] = $course_id; //课程ID
                            $cell['duration'] = $duration; //上课时长
                            $cell['weekday'] = $weekday; //星期
                            $cell['campus_id'] = $campus_id; //校区ID
                            $sava_cell_date[] = $cell;
                        }
                    }

                }

                if(count($sava_cell_date) > 0){
                    if (!(new StudentSubjectInfosClassModel())->insertAll($sava_cell_date)) {
						throw new BaseException('SCHEDULE_CLASS_FAILED');
                    }

                }else{

						throw new BaseException('CLASS_NOT_SCHEDULE');
                }

                if (!(new StudentSubjectClassModel())->insertAll($save_data)) {
						throw new BaseException('BREAKDOWN_FAILURE');
                }
            }

            //修改开班状态
            $result = (new StudentSubjectClassModel())->where(['class_subject_id' => $class_id])->select();
            if(count($result) > 0){
                if(!(new GradesDetailsModel())->update(['status' => 1],['id' => $class_id])){
                    throw new BaseException('UPDATE_OPEN_GRADES_RECORD_FAILED');
                }

            }else{
                if(!(new GradesDetailsModel())->update(['status' => 0],['id' => $class_id])){
                    throw new BaseException('UPDATE_OPEN_GRADES_RECORD_FAILED');
                }
            }

  
      
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	 /**
     * 分班
     * User: chenben
     * Date: 2020/04/18.
     *
     * @param $params
     *
     * @return array
     */
    public function classAssignment($params)
    {
        try {
			$data = [];
			  //已报课程详情列表
			$course_assignment_arr = [];
            $result_assignment_arr = (new CourseLogModel())->order('create_time desc')->select();
            array_splice($course_assignment_arr, 0, count($course_assignment_arr));  //清空数组
            foreach ($result_assignment_arr as $key=>$value){
                $item = [];
                $item['id'] = $value['id']; //id
                $item['course'] = $value['course']; //课程
                $item['campus'] = $value['campus']; //校区
                $item['contract_number'] = $value['contract_number']; //订单编号
                $item['status'] = $value['status']; //付款状态
                $item['record_status'] = $value['record_status']; //报读来源
                $course_assignment_arr[] = $item;

            }
			
            $course_id = $params['course_id']; //课程id
            $course_name = $params['course_name']; //课程名称
            $class_id = $params['id']; //班级ID
            $room_id = $params['room_id']; //教室ID
            $campus_id = $params['campus_id']; //校区ID

            for($k =0; $k < count($course_assignment_arr); $k ++){
                if(strpos($course_assignment_arr[$k]['course'],''.$course_id) !== false){//包含
                    $result = (new ContractModel())->get(['contract_number' => $course_assignment_arr[$k]['contract_number']]);
                    $item = [];
                    if($course_assignment_arr[$k]['record_status'] == 1){ //课程
                        $explode_arr = explode(",",$result['course']);
                        $explode_elimination_arr = explode(",",$result['course_elimination']);
                        $explode_elimination_arr_give = explode(",",$result['give_course_nums']);
						$explode_elimination_arr_paid = explode(",",$result['course_paid_nums']);
                        for($j = 0; $j < count($explode_arr); $j ++){
                            if($explode_arr[$j] == $course_id){
                                $item['course_elimination'] = $explode_elimination_arr[$j];
                                $item['course_elimination_give'] = $explode_elimination_arr_give[$j];
								$item['course_elimination_paid'] = $explode_elimination_arr_paid[$j];
                                break;
                            }

                        }
                        $res = (new StudentSubjectClassModel())->get(['contract_number' => $course_assignment_arr[$k]['contract_number'],  'status' => 1, 'class_subject_id' => $class_id]);
                        if($res){
                            $item['status_match'] = 1;
                        }else{
                            $item['status_match'] = 0;
                        }
                        $item['student_name'] = $result['student_name'];
                        $item['id'] = $course_assignment_arr[$k]['id'];
                        $item['course'] = $course_assignment_arr[$k]['course'];
                        $item['campus'] = $course_assignment_arr[$k]['campus'];
                        $item['type'] = 1;
                        $item['contract_number'] = $course_assignment_arr[$k]['contract_number'];
                        $item['student_id'] = $result['student_id'];
                        if($result['status'] == 1){
                            $item['status_text'] = '已付款';
                        }else if($result['status'] == 2){
                            $item['status_text'] = '未付款';
                        }else if($result['status'] == 3){
                            $item['status_text'] = '部分付款';
                        }
                        $item['course_name'] = $course_name.'(课程)';
                        $data[] = $item;

                    }else if($course_assignment_arr[$k]['record_status'] == 2){  //班级
                        $explode_arr = explode(",",$result['grades_course']);
                        $explode_elimination_arr = explode(",",$result['grades_course_elimination']);
                        $explode_elimination_arr_give = explode(",",$result['give_grades_course_nums']);
						$explode_elimination_arr_paid = explode(",",$result['grades_course_paid_nums']);
                        for($j = 0; $j < count($explode_arr); $j ++){
                            if($explode_arr[$j] == $course_id){
                                $item['course_elimination'] = $explode_elimination_arr[$j];
                                $item['course_elimination_give'] = $explode_elimination_arr_give[$j];
								$item['course_elimination_paid'] = $explode_elimination_arr_paid[$j];
                                break;
                            }

                        }
                        $res = (new StudentSubjectClassModel())->get(['contract_number' => $course_assignment_arr[$k]['contract_number'],  'status' => 2, 'class_subject_id' => $class_id]);
                        if($res){
                            $item['status_match'] = 1;
                        }else{
                            $item['status_match'] = 0;
                        }
                        $item['student_name'] = $result['student_name'];
                        $item['id'] = $course_assignment_arr[$k]['id'];

                        $item['course'] = $course_assignment_arr[$k]['course'];
                        $item['campus'] = $course_assignment_arr[$k]['campus'];
                        $item['type'] = 2;
                        $item['contract_number'] = $course_assignment_arr[$k]['contract_number'];
                        $item['student_id'] = $result['student_id'];
                        if($result['status'] == 1){
                            $item['status_text'] = '已付款';
                        }else if($result['status'] == 2){
                            $item['status_text'] = '未付款';
                        }else if($result['status'] == 3){
                            $item['status_text'] = '部分付款';
                        }
                        $grades_name = (new GradesDetailsModel())->get(['id' => $class_id])['grades_name'];
                        $item['course_name'] = $grades_name.'【'.$course_name.'】'.'(班级)';
                        $data[] = $item;
                    }

                }
            }
			
			$this->data = $data;
			
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	 /**
     * 班级结业
     * User: chenben
     * Date: 2020/04/18.
     *
     * @param $params
     *
     * @return array
     */
    public function gradesDel($params)
    {
        try {
            //结业学员
            $grades_result = (new StudentSubjectInfosClassModel())->where(['class_subject_id' => $params['id']])->select();
            $student_arr = [];
            foreach ($grades_result as $key => $value){
                if($value['contract_number'] != null && $value['contract_number'] != '---'){
                    $item = [];
                    $item['id'] = $value['student_id'];
                    $item['conclusion_status'] = 1;
                    $student_arr[] = $item;

               }
            }
            if(count($student_arr) > 0){
                (new StudentModel())->saveAll($student_arr);  //更新状态
            }

            if (!(new GradesDetailsModel())->save(['graduation_status' => 1], ['id'=>$params['id']])) {
               throw new BaseException('UPDATE_GRADES_CLASS_FAILED');
            }

            if (!(new GradesDetailsListsModel())->where(['class_manage_id' => $params['id']])->update(['graduation_status' => 1])) {
               throw new BaseException('UPDATE_CLASS_STATUS_FAILED');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 新增班级
     * User: wufeng
     * Date: 2020/01/11.
     *
     * @param $params
     *
     * @return array
     */
    public function gradesAdd($params)
    {
        try {
            $data = [];
            //			$data['campus_id'] = xcxapi_get_current_campus_id();
            $data['campus_id'] = 1;
            $data['headmaster'] = $params['b_teacher_id'] ? $params['b_teacher_id'] : 0;
            $data['teacher'] = $params['t_teacher_id'] ? $params['t_teacher_id'] : 0;
            $data['assistant'] = $params['z_teacher_id'] ? $params['z_teacher_id'] : 0;
            $data['course_id'] = $params['course_id'];
            $data['class_name'] = $params['class_name'];
            $data['preoccupation'] = $params['preoccupation'];
            $data['class_room'] = $params['class_room'];
            $data['class_date'] = $params['class_date'];
            $data['start_date'] = $params['start_date'];
            $data['project_num'] = $params['project_num'];
            (new GradesModel())->save($data);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 获取班级信息
     * User: wufeng
     * Date: 2020/02/11.
     *
     * @param $params
     *
     * @return array
     */
    public function achieveGradesInfo($params)
    {
        try {
            $manage_id = $params['id'];
            //			$campus_id = xcxapi_get_current_campus_id();
            $campus_id = 1;
            // 控制来源
            $source_status = $params['status'];

            $grades_list = (new GradesDetailsModel())->get(['id' => $manage_id]);
            $gcourse_name = (new CourseModel())->get(['id' => $grades_list['course_id']])['course_name'];
            $grades_list['course_name'] = $gcourse_name;
            if (0 === $grades_list['preoccupation']) {
                $grades_list['preoccupation'] = '无限';
            }
            $data = [];
            $class_time_place_str = $grades_list['class_time_place']; //字符串

            $room_id_arr = explode(',', $grades_list['room_id']); //教室字符串数组
            $time_slot = explode(',', $grades_list['time_slot']); //时间段字符串数组
            $week_record = explode(',', $grades_list['week_record']); //星期字符串数组
            $room_text = explode(',', $grades_list['room_text']); //教室名称字符串数组

            if (1 === $grades_list['repeat_status']) { //按周
                for ($index = 0; $index < \count($room_id_arr); ++$index) {
                    $item['weekday'] = $week_record[$index];
                    $time_arr = explode('-', $time_slot[$index]);
                    $item['start_time'] = $time_arr[0];
                    $item['end_time'] = $time_arr[1];
                    $item['room_text'] = $room_text[$index];
                    $item['room_id'] = $room_id_arr[$index];

                    /*
                    if(get_current_campus_id() && (1 != get_current_group_id())) {  //非超管
                        $item['room_id'] = ClassRoomModel::get(['campus_id' => get_current_campus_id(),'class_name' => $class])['id'];
                    }else{  //超管
                        $item['room_id'] = ClassRoomModel::get(['class_name' => $class])['id'];
                    }
                    */

                    $data[] = $item;
                }
            } elseif (2 === $grades_list['repeat_status']) {  //按日
                $item['weekday'] = $week_record[0];
                $time_arr = explode('-', $time_slot[0]);
                $item['start_time'] = $time_arr[0];
                $item['end_time'] = $time_arr[1];
                $item['room_text'] = $room_text[0];
                $item['room_id'] = $room_id_arr[0];

                /*
                if(get_current_campus_id() && (1 != get_current_group_id())) {  //非超管
                    $item['room_id'] = ClassRoomModel::get(['campus_id' => get_current_campus_id(),'class_name' => $class])['id'];
                }else{  //超管
                    $item['room_id'] = ClassRoomModel::get(['class_name' => $class])['id'];
                }
                */
                $data[] = $item;
            }
            $json = json_encode($data);

            $where = [];
            $where['campus_id'] = $campus_id;
            $where['status'] = 1;
            $courses = (new CourseModel())->where($where)->select();
            $teacher_department = (new TeacherModel())->where($where)->field('teacher_department')->group('teacher_department')->select()->toArray();
            $teacher_subject = (new TeacherModel())->where($where)->field('teacher_subject')->group('teacher_subject')->select()->toArray();
            $teacher_grade = (new TeacherModel())->where($where)->field('teacher_grade')->group('teacher_grade')->select()->toArray();
            //获取
            $class_room = (new ClassRoomModel())->where($where)->select()->toArray();

            return $this->fetch('', [
                'course' => $courses,
                'class_room' => $class_room,
                'department' => $teacher_department,
                'jsonstr' => $json,
                'source_status' => $source_status,
                'manage_id' => $manage_id,
                'campus_id' => $campus_id,
                'subject' => $teacher_subject,
                'grades_list' => $grades_list,
                'grade' => $teacher_grade,
            ]);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
	 * 排课冲突判断
	 * User: wufeng
	 * Date: 2020/04/20
	 *
	 * @param $course_item
	 * @param $modify_status
	 * @param $manage_id
	 * @param $public_campus_id
	 * @return int
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    public function judgement_conflict($course_item, $modify_status, $manage_id, $public_campus_id)
    {
        $status_course = false;
        $current_campus_id = $public_campus_id; //当前校区
		//排课详情信息
        $result_course_lists = (new GradesDetailsListsModel())->where(['campus_id' => $current_campus_id])->select();
		$course_lists_arr = [];
        array_splice($course_lists_arr, 0, count($course_lists_arr));  //清空数组
        foreach ($result_course_lists as $key=>$value){
                    $item = [];
                    $item['class_date'] = $value['class_date']; //开课日期
                    $item['class_manage_id'] = $value['class_manage_id']; //教室管理详情表自增id
                    $item['course_id'] = $value['course_id']; //课程ID
                    $item['campus_id'] = $value['campus_id']; //归属校区
                    $item['weekday'] = $value['weekday']; //星期
                    $item['headmaster'] = $value['headmaster']; //班主任
                    $item['teacher'] = $value['teacher']; //任课老师
                    $item['assistant'] = $value['assistant']; //助教
                    $item['class_grades_name'] = $value['class_grades_name']; //班级名称
                    $item['class_subject_start'] = $value['class_subject_start']; //上课开始时间
                    $item['class_subject_end'] = $value['class_subject_end']; //上课结束时间
                    $item['class_room_id'] = $value['class_room_id']; //教室id
                    $item['class_room'] = $value['class_room']; //教室名称
                    $item['status'] = $value['status']; //上课状态
                    $course_lists_arr[] = $item;
        }
       for($a = 0; $a < count($course_lists_arr); $a ++){

            if($modify_status && $course_lists_arr[$a]['class_manage_id'] == $manage_id){
                continue;
            }

            if($course_lists_arr[$a]['campus_id'] == $current_campus_id){  //校区是否相同
                    if($course_lists_arr[$a]['class_date'] == $course_item['class_date']){ //日期是否相同

                        $course_list_start_timestamp = strtotime($course_lists_arr[$a]['class_subject_start']);  //课程开始时间
                        $course_list_end_timestamp = strtotime($course_lists_arr[$a]['class_subject_end']);  //课程结束时间
                        $course_item_start_timestamp = strtotime($course_item['class_subject_start']);  //课程开始时间
                        $course_item_end_timestamp = strtotime($course_item['class_subject_end']);  //课程结束时间

                        if($course_lists_arr[$a]['class_room_id'] == $course_item['class_room_id']){  //教室是否相同

                            //判断教室是否冲突
                            if($course_item_end_timestamp <= $course_list_start_timestamp){
                                if($course_lists_arr[$a]['teacher'] == $course_item['teacher']){  //任课老师是否相同
                                    //1.判断老师时间是否冲突
                                    //2.如果老师时间不冲突则比较助教是否相
                                    //3.比较助教相同的条件下时间是否冲突

                                    if($course_item_end_timestamp <= $course_list_start_timestamp){
                                        //任课老师时间不冲突
                                        if($course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                            if($course_item_end_timestamp <= $course_list_start_timestamp){
                                                //可排
                                                $status_course = false;
                                            }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                                //可排
                                                $status_course = false;
                                            }else{

                                                //不可排
                                                $status_course = true;
                                                return  1;   //助教时间冲突
                                            }


                                        }else{
                                            //可排
                                            $status_course = false;
                                        }

                                    }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                        //任课老师时间不冲突
                                        if($course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                            if($course_item_end_timestamp <= $course_list_start_timestamp){
                                                //可排
                                                $status_course = false;
                                            }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                                //可排
                                                $status_course = false;
                                            }else{

                                                //不可排
                                                $status_course = true;
                                                return  1;   //助教时间冲突
                                            }



                                        }else{
                                            //可排
                                            $status_course = false;
                                        }


                                    }else{
                                        //不可排
                                        $status_course = true;
                                        return  2;   //老师时间冲突
                                    }



                                }else if($course_lists_arr[$a]['teacher'] != $course_item['teacher']){
                                    if($course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                        //比时间
                                        if($course_item_end_timestamp <= $course_list_start_timestamp){
                                            //可排
                                            $status_course = false;

                                        }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                            //可排
                                            $status_course = false;

                                        }else{
                                            //不可排
                                            $status_course = true;
                                            return  1;   //助教时间冲突
                                        }

                                    }

                                }

                            }else if($course_item_start_timestamp >= $course_list_end_timestamp){

                                if($course_lists_arr[$a]['teacher'] == $course_item['teacher']){  //任课老师是否相同
                                    //1.判断老师时间是否冲突
                                    //2.如果老师时间不冲突则比较助教是否相
                                    //3.比较助教相同的条件下时间是否冲突

                                    if($course_item_end_timestamp <= $course_list_start_timestamp){
                                        //任课老师时间不冲突
                                        if($course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                            if($course_item_end_timestamp <= $course_list_start_timestamp){
                                                //可排
                                                $status_course = false;
                                            }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                                //可排
                                                $status_course = false;
                                            }else{

                                                //不可排
                                                $status_course = true;
                                                return  1;   //助教时间冲突
                                            }


                                        }else{
                                            //可排
                                            $status_course = false;
                                        }

                                    }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                        //任课老师时间不冲突
                                        if($course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                            if($course_item_end_timestamp <= $course_list_start_timestamp){
                                                //可排
                                                $status_course = false;
                                            }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                                //可排
                                                $status_course = false;
                                            }else{

                                                //不可排
                                                $status_course = true;
                                                return  1;   //助教时间冲突
                                            }



                                        }else{
                                            //可排
                                            $status_course = false;
                                        }


                                    }else{
                                        //不可排
                                        $status_course = true;
                                        return  2;   //老师时间冲突
                                    }



                                }else if($course_lists_arr[$a]['teacher'] != $course_item['teacher']){
                                    if($course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                        //比时间
                                        if($course_item_end_timestamp <= $course_list_start_timestamp){
                                            //可排
                                            $status_course = false;

                                        }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                            //可排
                                            $status_course = false;

                                        }else{
                                            //不可排
                                            $status_course = true;
                                            return  1;   //助教时间冲突
                                        }

                                    }

                                }
                            }else{
                                //不可排
                                $status_course = true;
                                return  3;   //教室时间冲突
                            }


                        }else if($course_lists_arr[$a]['class_room_id'] != $course_item['class_room_id']){  //教室不同
                            if($course_lists_arr[$a]['teacher'] == $course_item['teacher']){  //任课老师是否相同
                                //1.判断老师时间是否冲突
                                //2.如果老师时间不冲突则比较助教是否相同
                                //3.比较助教相同的条件下时间是否冲突
                                if($course_item_end_timestamp <= $course_list_start_timestamp){
                                    //任课老师时间不冲突
                                    if($course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                        if($course_item_end_timestamp <= $course_list_start_timestamp){
                                            //可排
                                            $status_course = false;
                                        }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                            //可排
                                            $status_course = false;
                                        }else{

                                            //不可排
                                            $status_course = true;
                                            return  1;   //助教时间冲突
                                        }


                                    }else{
                                        //可排
                                        $status_course = false;
                                    }

                                }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                    //任课老师时间不冲突
                                    if($course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                        if($course_item_end_timestamp <= $course_list_start_timestamp){
                                            //可排
                                            $status_course = false;
                                        }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                            //可排
                                            $status_course = false;
                                        }else{

                                            //不可排
                                            $status_course = true;
                                            return  1;   //助教时间冲突
                                        }



                                    }else{
                                        //可排
                                        $status_course = false;
                                    }


                                }else{
                                    //不可排
                                    $status_course = true;
                                    return  2;   //老师时间冲突
                                }



                            }else if($course_lists_arr[$a]['teacher'] != $course_item['teacher']){
                                if($course_lists_arr[$a]['assistant'] == $course_item['assistant']){  //助教老师是否相同
                                                                        //比时间是否冲突
                                    if($course_item_end_timestamp <= $course_list_start_timestamp){
                                        //可排
                                        $status_course = false;

                                    }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                        //可排
                                        $status_course = false;

                                    }else{
                                        //不可排
                                        $status_course = true;
                                        return  1;   //助教时间冲突
                                    }


                                }
                            }

                        }

                    }

            }


        }


        return -1;
    }

    /**
     * 班级详情/课表/学员列表/
     * User: wufeng
     * Date: 2020/02/11.
     *
     * @param $params
     *
     * @return array
     */
    public function gradesDetail($params)
    {
        try {
            //班级详情
            $this->data['grades_info'] = (new GradesDetailsModel())->get($params['id']);
            //开班状态
            if (1 === (int) $this->data['grades_info']['status']) {
                $this->data['grades_info']['offer_course'] = '已开班';
            } elseif (0 === (int) $this->data['grades_info']['status']) {
                $this->data['grades_info']['offer_course'] = '未开班';
            }
            //课程类别
            $arrs = (new StudentSubjectClassModel())->where('class_subject_id', $params['id'])->column('student_id');
            //已报
            $this->data['grades_info']['already_reported_num'] = \count(array_unique($arrs));
            //教室
            $this->data['grades_info']['room'] = (implode('|', array_unique(explode(',', $this->data['grades_info']['room_text']))));
            //课程名称
            $this->data['grades_info']['course_name'] = (new CourseModel())->get($this->data['grades_info']['course_id'])['course_name'];
            //课表
            $where = $_where = [];
            $where['class_manage_id'] = $params['id'];
            $this->data['school_timetable'] = (new GradesDetailsListsModel())
                ->where($where)
                ->order('class_date asc')
                ->select()
                ->toArray();
            $i = 0;
            foreach ($this->data['school_timetable'] as &$val) {
                $i = $i + 1;
                $val['class_day'] = '第'.$i.'节';
                $val['class_weekday_datetime'] = $val['class_date'].' '.$val['weekday'].' '.$val['class_subject_start'].'-'.$val['class_subject_end'];
                $val['actual_number'] = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $val['id'], 'attendance' => 1])->count();
                $val['should_number'] = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $val['id']])->count();
            }
            //学员列表
            $_where['class_subject_id'] = $params['id'];
            $this->data['student_lists'] = (new StudentSubjectClassModel())
                ->where($_where)
				->order('id desc')
                ->select()
                ->toArray();
            foreach ($this->data['student_lists'] as &$val) {
                $val['already_arranged_num'] = (new StudentSubjectInfosClassModel())->where(['class_subject_id' => $val['class_subject_id'], 'student_id' => $val['student_id']])->count();
                //1:课程分配  2:班级分配  3:试听分配
                if (1 === (int) $val['status']) {
                    $contract_number = (new StudentSubjectClassModel())->get(['class_subject_id' => $val['class_subject_id'], 'student_id' => $val['student_id'], 'status' => $val['status']])['contract_number'];
                    $course_str = (new ContractModel())->get($contract_number)['course'];
					$course_arr = explode(',',$course_str);
					$i = array_search($this->data['grades_info']['course_id'],$course_arr, true);
					$course_paid_nums_str = (new ContractModel())->get($contract_number)['course_paid_nums'];
					$course_elimination_str = (new ContractModel())->get($contract_number)['course_elimination'];
					$course_paid_nums_arr = explode(',',$course_paid_nums_str);
					$course_elimination_arr = explode(',',$course_elimination_str);
					$val['paid_nums'] = $course_paid_nums_arr[$i];
					$val['elimination'] = $course_elimination_arr[$i];
					$val['surplus'] = $val['paid_nums'] - $val['elimination'];
                } elseif (2 === (int) $val['status']) {
                    $contract_number = (new StudentSubjectClassModel())->get(['class_subject_id' => $val['class_subject_id'], 'student_id' => $val['student_id'],
                        'status' => $val['status'], ])['contract_number'];
					$course_str = (new ContractModel())->get($contract_number)['course'];
					$course_arr = explode(',',$course_str);
					$grades_course_paid_nums_str = (new ContractModel())->get($contract_number)['grades_course_paid_nums'];
					$grades_course_elimination_str = (new ContractModel())->get($contract_number)['grades_course_elimination'];
					$grades_course_paid_nums_arr = explode(',',$grades_course_paid_nums_str);
					$grades_course_elimination_arr = explode(',',$grades_course_elimination_str);
					$i = array_search($this->data['grades_info']['course_id'],$course_arr, true);
					$val['paid_nums'] = $grades_course_paid_nums_arr[$i];
					$val['elimination'] = $grades_course_elimination_arr[$i];
					$val['surplus'] = $val['paid_nums'] - $val['elimination'];
                }
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
	 * User: wufeng
	 * Date: 2020/03/07
	 *
	 * @param $params
	 * @return array
	 */
    public function addStudent($params)
    {
        try {
            //班级详情
            $this->data['grades_info'] = (new GradesDetailsModel())->get($params['id']);
            //开班状态
            if (1 === (int) $this->data['grades_info']['status']) {
                $this->data['grades_info']['offer_course'] = '已开班';
            } elseif (0 === (int) $this->data['grades_info']['status']) {
                $this->data['grades_info']['offer_course'] = '未开班';
            }
            //课程类别
            $arrs = (new StudentSubjectClassModel())->where('class_subject_id', $params['id'])->column('student_id');
            //已报
            $this->data['grades_info']['already_reported_num'] = \count(array_unique($arrs));
            //教室
            $this->data['grades_info']['room'] = (implode('|', array_unique(explode(',', $this->data['grades_info']['room_text']))));
            //课程名称
            $this->data['grades_info']['course_name'] = (new CourseModel())->get($this->data['grades_info']['course_id'])['course_name'];
            //课表
            $where = $_where = [];
            $where['class_manage_id'] = $params['id'];
            $this->data['school_timetable'] = (new GradesDetailsListsModel())
                ->where($where)
                ->order('class_date asc')
                ->select()
                ->toArray();
            $i = 0;
            foreach ($this->data['school_timetable'] as &$val) {
                $i = $i + 1;
                $val['class_day'] = '第'.$i.'节';
                $val['class_weekday_datetime'] = $val['class_date'].' '.$val['weekday'].' '.$val['class_subject_start'].'-'.$val['class_subject_end'];
                $val['actual_number'] = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $val['id'], 'attendance' => 1])->count();
                $val['should_number'] = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $val['id']])->count();
            }
            //学员列表
            $_where['class_subject_id'] = $params['id'];
            $this->data['student_lists'] = (new StudentSubjectClassModel())
                ->where($_where)
                ->select()
                ->toArray();
            foreach ($this->data['student_lists'] as &$val) {
                $val['already_arranged_num'] = (new StudentSubjectInfosClassModel())->where(['class_subject_id' => $val['class_subject_id'], 'student_id' => $val['student_id']])->count();
                //1:课程分配  2:班级分配  3:试听分配
                if (1 === (int) $val['status']) {
                    $contract_number = (new StudentSubjectClassModel())->get(['class_subject_id' => $val['class_subject_id'], 'student_id' => $val['student_id'], 'status' => $val['status']])['contract_number'];
                    $course_str = (new ContractModel())->get($contract_number)['course'];
					$course_arr = explode(',',$course_str);
					$i = array_search($this->data['grades_info']['course_id'],$course_arr, true);
					$course_paid_nums_str = (new ContractModel())->get($contract_number)['course_paid_nums'];
					$course_elimination_str = (new ContractModel())->get($contract_number)['course_elimination'];
					$course_paid_nums_arr = explode(',',$course_paid_nums_str);
					$course_elimination_arr = explode(',',$course_elimination_str);
					$val['paid_nums'] = $course_paid_nums_arr[$i];
					$val['elimination'] = $course_elimination_arr[$i];
					$val['surplus'] = $val['paid_nums'] - $val['elimination'];
                } elseif (2 === (int) $val['status']) {
                    $contract_number = (new StudentSubjectClassModel())->get(['class_subject_id' => $val['class_subject_id'], 'student_id' => $val['student_id'],
                        'status' => $val['status'], ])['contract_number'];
					$course_str = (new ContractModel())->get($contract_number)['course'];
					$course_arr = explode(',',$course_str);
					$grades_course_paid_nums_str = (new ContractModel())->get($contract_number)['grades_course_paid_nums'];
					$grades_course_elimination_str = (new ContractModel())->get($contract_number)['grades_course_elimination'];
					$grades_course_paid_nums_arr = explode(',',$grades_course_paid_nums_str);
					$grades_course_elimination_arr = explode(',',$grades_course_elimination_str);
					$i = array_search($this->data['grades_info']['course_id'],$course_arr, true);
					$val['paid_nums'] = $grades_course_paid_nums_arr[$i];
					$val['elimination'] = $grades_course_elimination_arr[$i];
					$val['surplus'] = $val['paid_nums'] - $val['elimination'];
                }
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 点名上课列表
     * User: wufeng
     * Date: 2020/02/12.
     *
     * @param $params
     *
     * @return array
     */
    public function rollCallLists($params)
    {
        try {
            $json = '';
            $class_status = 0;
            $content_area = '';
            $remarks_area = '';
            $id = $params['id']; //节课id
            $campus_id = 1;
            //				$campus_id = xcxapi_get_current_campus_id();
            $class_manage_id = $this->gradesDetailsListsModel->get(['id' => $id])['class_manage_id'];
            $class_status = $this->gradesDetailsModel->get(['id' => $class_manage_id])['class_status'];
            $key_json = 'jsonstudent';
            $key_status = 'status';
            $json_session = session($key_json);
            $content_area = session('content_area'); //课节内容
                $remarks_area = session('remarks_area'); //课节备注
                $json = json_decode($json_session);
            if (\count($json) > 0) {
                $search_name = '';
                if (1 === session($key_status)) {
                    $search_name = session('find_name');
                }

                return $this->fetch('', [
                    'class_status' => $class_status,
                    'jsondata' => $json_session,
                    'id' => $id,
                    'campus_id' => input('campus_id'),
                    'search_name' => $search_name,
                    'content_area' => $content_area,
                    'remarks_area' => $remarks_area,
                ]);
            }
            $result = $this->studentsubjectinfosclassModel->where(['class_manage_details_id' => $id])->select();
            $where = [];
            $where['campus_id'] = $campus_id;
            $student_result = $this->studentModel->where($where)->where(['status' => 1])->select();
            $where['class_subject_id'] = $class_manage_id; //班级ID
            $student_result_list = $this->studentsubjectclassModel->where($where)->select();
            $student_data = [];
            foreach ($student_result as $key => $value) {
                $student_data[$value['id'].''] = $value['phone'];
            }

            $student_result_list_data = [];
            foreach ($student_result_list as $key => $value) {
                $item = [];
                $item['class_subject_id'] = $value['class_subject_id'];
                $item['student_type'] = $value['student_type'];
                $item['room_id'] = $value['room_id'];
                $item['student_id'] = $value['student_id'];
                $item['status'] = $value['status'];
                $item['contract_number'] = $value['contract_number'];
                $student_result_list_data[] = $item;
            }

            $data_json = [];   //返回前台json
            foreach ($result as $key => $value) {
                $item = [];
                $student_type = 1;
                for ($a = 0; $a < \count($student_result_list_data); ++$a) {
                    if ($student_result_list_data[$a]['contract_number'] === $value['contract_number'] && $student_result_list_data[$a]['status'] === $value['report_status'] && $student_result_list_data[$a]['room_id'] === $value['room_id'] && $student_result_list_data[$a]['class_subject_id'] === $value['class_subject_id'] && $student_result_list_data[$a]['student_id'] === $value['student_id']) {
                        $student_type = $student_result_list_data[$a]['student_type']; //学员类型
                    }
                }

                if (1 === $student_type) {
                    $item['student_name'] = $value['student_name']; //非补课学员
                } elseif (2 === $student_type) {
                    $item['student_name'] = $value['student_name'].'_【临加】'; //临加学员
                } elseif (3 === $student_type) {
                    $item['student_name'] = $value['student_name'].'_【补课】'; //补课学员
                } elseif (4 === $student_type) {
                    $item['student_name'] = $value['student_name'].'_【试听】'; //试听学员
                }

                $item['student_type'] = $student_type; //学生类型
                $item['class_manage_details_id'] = $value['class_manage_details_id'];
                $item['seat_number'] = $value['seat_number'];
                $item['class_subject_id'] = $value['class_subject_id'];
                $item['room_id'] = $value['room_id'];
                $item['student_id'] = $value['student_id'];
                $item['surplus_class_elimination'] = $value['surplus_class_elimination'].'(赠送'.$value['surplus_class_elimination_give'].')'; //剩余课时
                    $item['surplus_class_elimination_give'] = $value['surplus_class_elimination_give']; //赠送剩余课时
                    $item['id'] = $value['id'];
                $item['phone'] = $student_data[$value['student_id'].''];
                $data_json[] = $item;
            }
            $json = json_encode($data_json);
            session($key_json, $json);
            session($key_status, -1);
            session('find_name', null);

            return $this->fetch('', [
                'class_status' => $class_status,
                'jsondata' => $json,
                'id' => input('id'),
                'search_name' => '',
                'content_area' => $content_area,
                'campus_id' => input('campus_id'),
                'remarks_area' => $remarks_area,
            ]);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 点名上课
     * User: wufeng
     * Date: 2020/02/19.
     *
     * @param $params
     *
     * @return array
     */
    public function rollCall($params)
    {
        try {
            $json = '';
            $class_status = 0;
            $content_area = '';
            $remarks_area = '';
            $id = $params['id']; //节课id
            $campus_id = 1;
//                $campus_id = xcxapi_get_current_campus_id();
            $key_json = 'jsonstudent';
            $key_status = 'status';
            $student_name = $params['student_name']; //搜索名称
                $student_lists = $params['student_lists']; //学生列表
                $content_area = $params['content_area']; //课节内容
                $remarks_area = $params['remarks_area']; //课节备注
                $student_lists = json_decode($student_lists, true);
            $data_json = [];   //返回前台json
            for ($i = 0; $i < \count($student_lists); ++$i) {
                $cell = $student_lists[$i];
                $item = [];
                if (false !== strpos($cell['student_name'], $student_name)) {
                    $item['student_name'] = $cell['student_name'];
                    $item['class_manage_details_id'] = $cell['class_manage_details_id'];
                    $item['seat_number'] = $cell['seat_number'];
                    $item['class_subject_id'] = $cell['class_subject_id'];
                    $item['room_id'] = $cell['room_id'];
                    $item['student_id'] = $cell['student_id'];
                    $item['surplus_class_elimination'] = $cell['surplus_class_elimination']; //剩余课时
                        $item['surplus_class_elimination_give'] = $cell['surplus_class_elimination_give']; //赠送剩余课时
                        $item['id'] = $cell['id'];
                    $item['student_type'] = $cell['student_type'];
                    $item['phone'] = $cell['phone'];
                    $data_json[] = $item;
                }
            }

            if (\count($data_json) <= 0) {
                $this->error('未搜索到该学生', null, -1, 1);
            }
            $json = json_encode($data_json);
            session($key_json, $json);
            session($key_status, 1);
            session('find_name', $student_name);
            session('content_area', $content_area);  //课节内容
                session('remarks_area', $remarks_area); //课节备注
                $this->success('完成搜索', '', '', 1);

            session('find_name', null);

            return $this->fetch('', [
                'class_status' => $class_status,
                'jsondata' => $json,
                'id' => input('id'),
                'search_name' => '',
                'content_area' => $content_area,
                'campus_id' => input('campus_id'),
                'remarks_area' => $remarks_area,
            ]);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
	 * 新增班級
	 * User: wufeng
	 * Date: 2020/04/10
	 *
	 * @param $params
	 * @return array
	 */
    public function addclassdata($params)
    {
		try {
			$data = $params;
			
			//表示补课班级
			if($data['grades_name'] == -1){
				$course_name= (new CourseModel())->get(['id' => $data['course_id']])['course_name'];
				$course_name_ = $course_name.'_补课班级';
				$gradesdetail = [];
				$gradesdetail['grades_name'] = ['like', $course_name_.'%'];
				$count = (new GradesDetailsModel())->where($gradesdetail)->count();
				$data['grades_name'] = $course_name.'_补课班级_'.($count + 1).'_班';
			}
				
			
			//获取节假日信息
			$holiday_arr = [];
			$result_msg = (new HolidayModel())->where(['company_id'=>xcxapi_get_current_company_id()])->select();
			foreach ($result_msg as $key=>$value){
				$holiday_arr[] = $value['date_name'];
			}
			
            $status_num = $data['status'];
            $conflict =   $data['conflict'];
            //修改逻辑
            $modify_status = false;
            $manage_id = -1000;
            if($data['manage_id'] != -1){//是否存在"id"的参数
                $manage_id = $data['manage_id'];  //班级id
                $modify_status = true;
            }

            $course_id = $data['course_id'];  //课程id
            $holiday_status = $data['holiday_status']; //是否跳过节假日
            $grades_name = $data['grades_name'];//班级名称
            $headmaster = $data['headmaster'];//班主任
            $preoccupation = $data['preoccupation'];//预招学生
            $teacher = $data['teacher'];//任课老师
            $assistant = $data['assistant'];//助教
            $class_start_date = $data['class_start_date'];//计划开班
            $class_end_date = $data['class_end_date'];//计划结业
            $remarks = $data['remarks'];//备注
            $repeat_status = $data['repeat_status'];//重复类型；1：按周重复，2：按日重复
            $project_num = $data['project_num'];//计划课次
            $interval_value = $data['interval_value'];//重复间隔值：周重复则按根据interval_value的值来间隔重复;日重复则根据interval_value值间隔重复；默认间隔值为0
            $user_master_id = $data['user_master_id']; //班主任ID
            $teacher_id = $data['teacher_id']; //任课老师ID
            $assistant_id = $data['assistant_id']; //助教ID
            $res_teacher = (new UserModel())->get(['teacher_id' => $teacher_id, 'group_type' => 2]);
            $user_teacher_id = $res_teacher ? $res_teacher['id'] : null;
            $res_assistant = (new UserModel())->get(['teacher_id' => $assistant_id, 'group_type' => 3]);
            $user_assistant_id = $res_assistant ? $res_assistant['id'] : null;

            $campus_id = $data['campus_id']; //
            $classdata = $data['classdata'];  //排课数据
            $json_str =  $classdata;
            if(count($json_str) <= 0){
				throw new BaseException('NO_CLASS_TIME');
            }

            $str = "";
            $weekday_arr = [];
            $room_text_str = "";
            $room_id_str = "";
            $time_slot = "";
            $week_record = "";
            $start_day_class = "";
            $weekarray=array("星期日","星期一","星期二","星期三","星期四","星期五","星期六"); //先定义一个数组
            $start_postion = date("w",strtotime($class_start_date));
            for($i = 0 ; $i < count($json_str); $i ++){
                $item = $json_str[$i];
                $weekday = "";
                $weekday_mysql = "";
                if($repeat_status == 2){  //按日
                    $start_day_class = $item['weekday'];
                    $weekday = $weekarray[date("w",strtotime($item['weekday']))];
                }else if ($repeat_status == 1){  //按周
                    $weekday = $item['weekday'];
                    $weekday_mysql =  $item['weekday'];
                }
                $start_time = $item['start_time'];
                $end_time = $item['end_time'];
                $room_text = $item['room_text'];
                $room_id = $item['room_id'];
                if($repeat_status == 2){  //按日
                    $weekday = $item['weekday'].'--每隔'.$interval_value.'日';
                    $weekday_mysql = $item['weekday'];
                }
                $str = $str."【".$weekday.'--'.$start_time.'--'.$end_time.'--'.$room_text."】";
                $room_id_str = $room_id_str.','.$room_id;  //教室
                $room_text_str = $room_text_str.','.$room_text; //教室名称
                $week_record = $week_record.','.$weekday_mysql;  //星期
                $time_slot = $time_slot.','.$start_time.'-'.$end_time; //开始结束时间
            }

            $room_id_str = trim($room_id_str);
            $room_text_str = trim($room_text_str);
            $week_record = trim($week_record);
            $time_slot = trim($time_slot);

            $room_id_str = substr($room_id_str, 1, strlen($room_id_str));
            $room_text_str = substr($room_text_str, 1, strlen($room_text_str));
            $week_record = substr($week_record, 1, strlen($week_record));
            $time_slot = substr($time_slot, 1, strlen($time_slot));

            $class_time_place = $str;
            $already_class = "";//已排次数
            $already_arranged = "";//上课进度，已上次数
            $status = ""; //0：未上课，1：上课中
            $public_end_date = "";
            $have_end_date_status = false; //表示设置在了结束日期

            if($class_end_date == ""){  //未填写结业日期
                $public_end_date =  NULL;
            }else{
                $public_end_date = $class_end_date;
                $have_end_date_status = true;
            }

            //保存gradesdetailModel数据
            $savedata = array(

                'campus_id' => $campus_id,
                'course_id' => $course_id,
                'grades_name' => $grades_name,
                'headmaster' => $headmaster,
                'preoccupation' => $preoccupation,
                'teacher' => $teacher,
                'assistant' => $assistant,
                'holiday_status' => $holiday_status,
                'class_start_date'=> $class_start_date,
                'class_end_date' => $public_end_date,
                'remarks' => $remarks,
                'repeat_status' => $repeat_status,
                'project_num' => $project_num,
                'interval_value' => $interval_value,
                'room_id' => $room_id_str,
                'week_record' => $week_record,
                'time_slot' => $time_slot,
                'room_text' => $room_text_str,
                'class_time_place' => $class_time_place,
                'user_master_id' => $user_master_id,
                'teacher_id' => $teacher_id,
                'assistant_id' => $assistant_id,
                'user_teacher_id' => $user_teacher_id,
                'user_assistant_id' => $user_assistant_id,
                'user_edu_id' => xcxapi_get_current_user_id(),  //当前登录ID

            );

            if(!$modify_status){
                if((new GradesDetailsModel())->get(['grades_name' => $grades_name,'campus_id' =>$campus_id])){  //判断班级名称是否重复
					throw new BaseException('DUPLICATE_CLASS_NAME');
                }
            }


            $result = (new GradesDetailsModel())->create($savedata);
            if (!$result) {
                   	throw new BaseException('SCHEDULING_FAILURE');
                } else {
                    //插入班级详情表
                    $savedata_list = [];
                    $public_headmaster = $headmaster;  //公共班主任
                    $public_teacher = $teacher;  //公共任课老师
                    $public_assistant = $assistant;  //公共助教
                    $public_campus_id = $campus_id;  //公共校区
                    $public_course_id = $course_id;  //公共课程
                    $public_grades = $grades_name;  //公共班级名称


                    $init_day = "";
                    if($repeat_status == 1){
                        $init_day = $class_start_date; //开始日期
                    }else if($repeat_status == 2){
                        $init_day = $start_day_class; //开始日期
                    }
                    $timestamp = strtotime($init_day);

                for($num = 1; $num <= $project_num;) {


                    if($repeat_status == 1) {   //如果是按周重复
                        $postion = date("w",$timestamp);
                        $same_day = date("Y-m-d", $timestamp);
                        $public_end_date = $same_day;

                        if($have_end_date_status && strtotime($class_end_date) < strtotime($public_end_date) &&  $status_num == 2){  //填了结业日期

                            $sure_nums = $num-1; //可排次数
                            (new GradesDetailsModel())->where(['id'=> $result['id']])->delete();
							throw new BaseException('最多可排【'.$sure_nums.'】次课',400027);
                        }else if($have_end_date_status && strtotime($class_end_date) < strtotime($public_end_date)  &&  $status_num == 1){
                            $already_class =  $num-1; //可排次数;
                            break;
                        }


                        for($i = 0 ; $i < count($json_str); $i ++) {
                            $item = $json_str[$i];
                            $weekday = $item['weekday'];
                            if($weekarray[$postion] == $weekday) {
                                if($num -1 >= $project_num){
                                    $already_class =  $num-1; //可排次数;
                                    break;
                                }
                                //判断是否跳过节假日
                                if($holiday_status == 1){  //跳过节假日
                                    if(in_array($same_day,$holiday_arr)){
                                        break;
                                    }
                                }

                                $data = array();
                                $data['class_manage_id'] = $result['id'];
                                $data['headmaster'] = $public_headmaster;
                                $data['teacher'] = $public_teacher;
                                $data['assistant'] = $public_assistant;
                                $data['course_id'] = $public_course_id;
                                $data['campus_id'] = $public_campus_id;
                                $data['class_grades_name'] = $public_grades;
                                $data['class_date'] = $same_day;
                                $data['weekday'] = $item['weekday'];
                                $data['class_room_id'] = $item['room_id'];
                                $data['class_subject_start'] = $item['start_time'];
                                $data['class_subject_end'] = $item['end_time'];
                                $data['class_room'] = $item['room_text'];

                                //判断冲突
                                if($this->judgement_conflict($data, $modify_status, $manage_id, $public_campus_id ) == 1 && $conflict == 2){
                                    //助教冲突
                                    (new GradesDetailsModel())->where(['id'=> $result['id']])->delete();
                                    $msg = '忽略--【'.$same_day.'】--时间段:【'.$item['start_time'].'--'.$item['end_time'].'】---助教*【'.$public_assistant.'】冲突';
                                    throw new BaseException($msg, 400030);
                                }else if($this->judgement_conflict($data,$modify_status, $manage_id, $public_campus_id ) == 2 && $conflict == 2){
                                    //老师冲突
                                    (new GradesDetailsModel())->where(['id'=> $result['id']])->delete();
                                    $msg = '忽略--【'.$same_day.'】--时间段:【'.$item['start_time'].'--'.$item['end_time'].'】---任课老师*【'.$public_teacher.'】冲突';
                                    throw new BaseException($msg, 400030);
                                }else if($this->judgement_conflict($data,$modify_status, $manage_id, $public_campus_id ) == 3 && $conflict == 2){
                                    //教室冲突
                                    (new GradesDetailsModel())->where(['id'=> $result['id']])->delete();
									$msg = '忽略--【'.$same_day.'】--时间段:【'.$item['start_time'].'--'.$item['end_time'].'】---教室*【'. $item['room_text'].'】冲突';
                                    throw new BaseException($msg ,400030);
                                }else if(($this->judgement_conflict($data,$modify_status, $manage_id, $public_campus_id ) == 1 || $this->judgement_conflict($data,$modify_status, $manage_id, $public_campus_id ) == 2 || $this->judgement_conflict($data,$modify_status, $manage_id, $public_campus_id ) == 3) && $conflict == 3){


                                }else{
                                    $savedata_list[] = $data;
                                    $num++;
                                }
                              
                            }
                        }

                            if($postion == 0){  //周日
                                $days_add = $interval_value * 7;
                                $timestamp = strtotime('+'.$days_add.'days', $timestamp);
                            }
                            $timestamp = strtotime('+1days', $timestamp);


                    }else if($repeat_status == 2) {  //如果是按天重复

                        $same_day = date("Y-m-d", $timestamp);
                        $public_end_date = $same_day;


                        if ($have_end_date_status && strtotime($class_end_date) < strtotime($public_end_date) && $status_num == 2) {  //填了结业日期
                            $sure_nums = $num - 1; //可排次数
                            (new GradesDetailsModel())->where(['id' => $result['id']])->delete();
							throw new BaseException('最多可排【'.$sure_nums.'】次课',400027);
                        } else if ($have_end_date_status && strtotime($class_end_date) < strtotime($public_end_date) && $status_num == 1) {
                            $already_class = $num - 1; //可排次数;
                            break;
                        }


                        $weekday = $weekarray[date("w", $timestamp)];
                        //判断是否跳过节假日
                        $bool_holiday = false;
                        if ($holiday_status == 1) {  //跳过节假日
                            if (in_array($same_day, $holiday_arr)) {
                                /*
                                $timestamp = strtotime('+1days', $timestamp);
                                */
                                $bool_holiday = true;
                            }
                        }

                  if (!$bool_holiday) {
                        $data = array();
                        $data['class_manage_id'] = $result['id'];
                        $data['headmaster'] = $public_headmaster;
                        $data['teacher'] = $public_teacher;
                        $data['assistant'] = $public_assistant;
                        $data['course_id'] = $public_course_id;
                        $data['campus_id'] = $public_campus_id;
                        $data['class_grades_name'] = $public_grades;
                        $data['class_date'] = $same_day;
                        $data['weekday'] = $weekday;
                        $data['class_room_id'] = $item['room_id'];
                        $data['class_subject_start'] = $item['start_time'];
                        $data['class_subject_end'] = $item['end_time'];
                        $data['class_room'] = $item['room_text'];

                      //判断冲突
                      if($this->judgement_conflict($data,$modify_status, $manage_id, $public_campus_id ) == 1 && $conflict == 2){
                          //助教冲突
                          (new GradesDetailsModel())->where(['id'=> $result['id']])->delete();
                          $msg = '忽略--【'.$same_day.'】--时间段:【'.$item['start_time'].'--'.$item['end_time'].'】---助教*【'.$public_assistant.'】冲突';
						  throw new BaseException($msg,400030);
                      }else if($this->judgement_conflict($data,$modify_status, $manage_id, $public_campus_id ) == 2 && $conflict == 2){
                          //老师冲突
                          (new GradesDetailsModel())->where(['id'=> $result['id']])->delete();
                          $msg = '忽略--【'.$same_day.'】--时间段:【'.$item['start_time'].'--'.$item['end_time'].'】---任课老师*【'.$public_teacher.'】冲突';
                          throw new BaseException($msg,400030);
                      }else if($this->judgement_conflict($data,$modify_status, $manage_id, $public_campus_id ) == 3 && $conflict == 2){
                          //教室冲突
                          (new GradesDetailsModel())->where(['id'=> $result['id']])->delete();
                          $msg = '忽略--【'.$same_day.'】--时间段:【'.$item['start_time'].'--'.$item['end_time'].'】---教室*【'. $item['room_text'].'】冲突';
                          throw new BaseException($msg,400030);
                      }else if(($this->judgement_conflict($data,$modify_status, $manage_id, $public_campus_id ) == 1 || $this->judgement_conflict($data,$modify_status, $manage_id, $public_campus_id ) == 2 || $this->judgement_conflict($data,$modify_status, $manage_id, $public_campus_id ) == 3) && $conflict == 3){


                      }else{
                          $savedata_list[] = $data;
                          $num++;
                      }

                     }


                        $days_add = $interval_value * 1;
                        $timestamp = strtotime('+' . $days_add . 'days', $timestamp);
                        $timestamp = strtotime('+1days', $timestamp);

                    }

                }

                $already_class = $num - 1; //可排次数;

                if($class_end_date == ""){
                    (new GradesDetailsModel())->save(['class_end_date' => $public_end_date],['id' => $result['id']]);
                    $already_class = $project_num;
                }

                (new GradesDetailsModel())->save(['already_class' => $already_class],['id' => $result['id']]); //更新可排次数

                if(count($savedata_list) > 0) {
                    if (!(new GradesDetailsListsModel())->insertAll($savedata_list)) {
                       throw new BaseException('SCHEDULING_FAILURE');
                    }
                }


            }
            if($modify_status){
                (new GradesDetailsModel())->where(['id' => $manage_id])->delete();
                (new GradesDetailsListsModel())->where(['class_manage_id' => $manage_id])->delete();
				$msg = [];
				$msg['code'] = 1;
				$msg['data'] = $grades_name;
				$msg['msg'] = '修改成功';
				$this->msg = $msg;
            }
			$msg = [];
            $msg['code'] = 1;
			$msg['data'] = $grades_name;
			$msg['msg'] = '排班成功';
			$this->msg = $msg;
			
		} catch (\Exception $e) {
			$this->errorMessage($e, $params);
		}

		return $this->return;
    }

	/**
	 * 获取数据列表
	 * 课程/班主任/任课老师/助教
	 * 常用时间段/开始/结束/时长/教室
	 * User: wufeng
	 * Date: 2020/04/10
	 *
	 * @param $params
	 * @return array
	 */
    public function getDataLists($params)
    {
		try {
			$where = [];
			$where['campus_id'] = $params['campus_id'];
			$this->data['courses'] = (new CourseModel())
				->where($where)
				->order('id desc')
				->select()
				->toArray();

			$this->data['headmasters'] = (new UserModel())
				->where($where)
				->where(['group_type'=>4])
				->order('id desc')
				->select()
				->toArray();

			$this->data['teachers'] = (new TeacherModel())
				->where($where)
				->order('id desc')
				->select()
				->toArray();

			$this->data['common_time_periods'] = (new ClassTimeModel())
				->where($where)
				->where(['type'=>2])
				->order('id desc')
				->select()
				->toArray();

			$this->data['rooms'] = (new ClassRoomModel())
				->where($where)
				->where(['status'=>1,'seat_set'=>['neq','']])
				->order('id desc')
				->select()
				->toArray();

		} catch (\Exception $e) {
			$this->errorMessage($e, $params);
		}

		return $this->return;
    }

    /**
     * 实例化
     * User: wufeng
     * Date: 2020/02/12.
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->gradesDetailsListsModel = new GradesDetailsListsModel();
        $this->gradesDetailsModel = new GradesDetailsModel();
        $this->studentsubjectinfosclassModel = new StudentSubjectInfosClassModel();
        $this->studentModel = new StudentModel();
    }
}
